<template>
  <div class="order_detail-page">
    <!-- 顶部彩带 -->
    <section class="hero">
      <div class="hero-left">
        <h1>订单明细 · 每一份水果，都是甜的</h1>
        <p>查看每笔订单的明细、金额与爱心捐赠占比。</p>
        <div class="hero-stats">
          <div class="stat">
            <div class="stat-num">¥ {{ totalAmount.toLocaleString() }}</div>
            <div class="stat-label">当前页合计金额</div>
          </div>
          <div class="stat">
            <div class="stat-num">¥ {{ totalDonation.toLocaleString() }}</div>
            <div class="stat-label">当前页捐赠金额</div>
          </div>
          <div class="stat">
            <div class="stat-num">{{ tableData.length }}</div>
            <div class="stat-label">当前页明细条数</div>
          </div>
        </div>
      </div>
      <div class="hero-right">
        <svg viewBox="0 0 200 200" class="hero-illustration" aria-hidden="true">
          <defs>
            <linearGradient id="od-g1" x1="0" x2="1" y1="0" y2="1">
              <stop offset="0%" stop-color="#A5D6A7"/>
              <stop offset="100%" stop-color="#66BB6A"/>
            </linearGradient>
            <linearGradient id="od-g2" x1="1" x2="0" y1="0" y2="1">
              <stop offset="0%" stop-color="#81C784"/>
              <stop offset="100%" stop-color="#C5E1A5"/>
            </linearGradient>
          </defs>
          <circle cx="100" cy="100" r="75" fill="url(#od-g2)" opacity="0.3"/>
          <path d="M100 170 C 30 120, 10 90, 30 60 C 50 30, 85 40, 100 60 C 115 40, 150 30, 170 60 C 190 90, 170 120, 100 170 Z"
                fill="url(#od-g1)"/>
          <circle cx="60" cy="50" r="8" fill="#fff" opacity="0.8"/>
          <circle cx="140" cy="35" r="6" fill="#fff" opacity="0.6"/>
        </svg>
      </div>
    </section>

    <!-- 检索工具条 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchObj">
        <el-form-item label="订单号">
          <el-input v-model="searchObj.order_no" placeholder="如：ORDER2025..." clearable />
        </el-form-item>
        <el-form-item label="水果名称">
          <el-input v-model="searchObj.fruit_name" placeholder="如：苹果" clearable />
        </el-form-item>
<!--        <el-form-item label="捐赠≥">-->
<!--          <el-input-number v-model="searchObj.donationMin" :min="0" :step="0.01" />-->
<!--        </el-form-item>-->
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
          <!-- <el-button type="success" @click="openAdd">新增明细</el-button> -->
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-card>
      <el-table
          v-loading="loading"
          :data="tableData"
          style="width: 100%"
          :row-class-name="rowClass"
      >
        <el-table-column prop="order_no" label="订单号" width="140" />
        <el-table-column prop="fruit_name" label="水果名称" width="120" />
        <el-table-column prop="quantity" label="数量" width="90">
          <template #default="{ row }">
            <el-tag type="success">{{ row.quantity }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="unit_price" label="单价(¥)" width="110">
          <template #default="{ row }">¥ {{ money(row.unit_price) }}</template>
        </el-table-column>

        <el-table-column label="小计(¥)" width="120">
          <template #default="{ row }">
            <b>¥ {{ money(row.quantity * row.unit_price) }}</b>
          </template>
        </el-table-column>

        <el-table-column prop="donation_ratio" label="捐赠占比" width="130">
          <template #default="{ row }">
            <el-progress
                :percentage="Math.round(100 * (Number(row.donation_ratio)||0))"
                :stroke-width="12"
                striped
                :text-inside="true"
            />
          </template>
        </el-table-column>

        <el-table-column label="捐赠金额(¥)" width="140">
          <template #default="{ row }">
            <span style="color:#d84315;font-weight:700">
              ¥ {{ money(row.quantity * row.unit_price * (Number(row.donation_ratio)||0)) }}
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="isdel" label="状态" width="90">
          <template #default="{ row }">
            <el-tag :type="row.isdel ? 'info' : 'success'">
              {{ row.isdel ? '已删除' : '正常' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="openEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="remove(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          class="pagination"
          v-model:current-page="searchObj.current"
          v-model:page-size="searchObj.limit"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10,20,50,100]"
          @current-change="loadData"
          @size-change="handleSizeChange"
      />
    </el-card>

    <!-- 新增 / 编辑 弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.mode==='add' ? '新增订单明细' : '编辑订单明细'" width="560px">
      <el-form :model="form" label-width="110px">
        <el-form-item label="订单号" required>
          <el-input v-model="form.order_id" placeholder="如：ORDER2025xxxx" />
        </el-form-item>
        <el-form-item label="水果ID" required>
          <el-input v-model="form.fruit_id" placeholder="如：1001" />
        </el-form-item>
        <el-form-item label="数量" required>
          <el-input-number v-model="form.quantity" :min="1" />
        </el-form-item>
        <el-form-item label="单价(¥)" required>
          <el-input-number v-model="form.unit_price" :min="0" :step="0.01" />
        </el-form-item>
        <el-form-item label="捐赠占比(0~1)" required>
          <el-input-number v-model="form.donation_ratio" :min="0" :max="1" :step="0.01" />
        </el-form-item>

        <el-alert
            :title="`预估小计：¥ ${money(form.quantity*form.unit_price)}；捐赠：¥ ${money(form.quantity*form.unit_price*(Number(form.donation_ratio)||0))}`"
            type="success"
            show-icon
        />
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible=false">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import api from '@/api/order_detail_api.js'; // 需具备 page / add / edit / del

// 数据与检索
const tableData = ref([]);
const total = ref(0);
const loading = ref(false);

// ✅ 改为用 order_no + fruit_name 查询
const searchObj = ref({
  current: 1,
  limit: 10,
  order_no: '',     // 订单号（模糊）
  fruit_name: '',   // 水果名称（模糊）
  donationMin: null // 若后端支持，可继续传；不支持可不传
});

// 弹窗
const dialog = ref({ visible: false, mode: 'add' }); // add | edit
const form = ref({
  detail_id: null,
  order_id: '',
  fruit_id: '',
  quantity: 1,
  unit_price: 0,
  donation_ratio: 0
});

// 统计
const totalAmount = computed(() =>
    tableData.value.reduce((s, it) => s + Number(it.quantity||0) * Number(it.unit_price||0), 0)
);
const totalDonation = computed(() =>
    tableData.value.reduce((s, it) =>
        s + Number(it.quantity||0) * Number(it.unit_price||0) * Number(it.donation_ratio||0), 0)
);

// 工具
const money = (n) => (Number(n||0)).toFixed(2);
const cleanEmpty = (obj) => {
  const r = {};
  Object.entries(obj).forEach(([k,v]) => {
    if (v !== '' && v !== null && v !== undefined) r[k] = v;
  });
  return r;
};
const rowClass = ({ row }) => {
  const donate = Number(row.quantity||0) * Number(row.unit_price||0) * Number(row.donation_ratio||0);
  return donate > 100 ? 'row-highlight' : '';
};

const loadData = async () => {
  loading.value = true;
  try {
    const params = {
      ...cleanEmpty(searchObj.value),
      start: (searchObj.value.current - 1) * searchObj.value.limit,
      limit: searchObj.value.limit
    };

    const res = await api.page(params);
    const root = res?.data ?? res ?? {};
    const box = root.data ?? root;

    // 列表
    let list =
        (Array.isArray(box) ? box : null) ||
        box.data || box.list || box.records || box.rows || [];
    if (!Array.isArray(list) && Array.isArray(box?.data?.data)) list = box.data.data;

    // 总数
    let totalCnt =
        root.total ?? root.count ??
        box.total ?? box.count ?? box?.data?.total ?? box?.data?.count ??
        (Array.isArray(list) ? list.length : 0);

    // 字段映射（补齐 fruit_name / order_no）
    tableData.value = (list || []).map(it => ({
      detail_id: it.detail_id ?? it.detailId ?? it.id,
      order_id: it.order_id ?? it.orderId,
      order_no: it.order_no ?? it.orderNo,           // ✅ 确保有
      fruit_id: it.fruit_id ?? it.fruitId,
      fruit_name: it.fruit_name ?? it.fruitName,     // ✅ 确保有
      quantity: Number(it.quantity || 0),
      unit_price: Number(it.unit_price || 0),
      donation_ratio: Number(it.donation_ratio ?? 0),
      isdel: it.isdel ?? 0,
      ...it
    }));

    total.value = Number(totalCnt) || 0;
  } catch (e) {
    console.error(e);
    ElMessage.error('加载失败');
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索
const search = () => {
  searchObj.value.current = 1;
  loadData();
};

// 分页大小
const handleSizeChange = (val) => {
  searchObj.value.limit = val;
  searchObj.value.current = 1;
  loadData();
};

// 新增 / 编辑 / 删除
const openAdd = () => {
  dialog.value = { visible: true, mode: 'add' };
  form.value = {
    detail_id: null,
    order_id: '',
    fruit_id: '',
    quantity: 1,
    unit_price: 0,
    donation_ratio: 0
  };
};

const openEdit = (row) => {
  dialog.value = { visible: true, mode: 'edit' };
  form.value = {
    detail_id: row.detail_id,
    order_id: row.order_id,
    fruit_id: row.fruit_id,
    quantity: row.quantity,
    unit_price: row.unit_price,
    donation_ratio: row.donation_ratio
  };
};

const submit = async () => {
  if (!form.value.order_id) return ElMessage.warning('请输入订单号');
  if (!form.value.fruit_id) return ElMessage.warning('请输入水果ID');
  if (Number(form.value.quantity) <= 0) return ElMessage.warning('数量必须大于0');
  if (Number(form.value.unit_price) < 0) return ElMessage.warning('单价不能小于0');
  const r = Number(form.value.donation_ratio);
  if (isNaN(r) || r < 0 || r > 1) return ElMessage.warning('捐赠占比需在 0~1 之间');

  try {
    if (dialog.value.mode === 'add') {
      await api.add(form.value);
      ElMessage.success('新增成功');
    } else {
      await api.edit(form.value);
      ElMessage.success('修改成功');
    }
    dialog.value.visible = false;
    loadData();
  } catch (e) {
    console.error(e);
    ElMessage.error('保存失败');
  }
};

const remove = async (row) => {
  try {
    await ElMessageBox.confirm(`确定删除明细 #${row.detail_id} 吗？`, '提示', { type: 'warning' });
    await api.del(row.detail_id);
    ElMessage.success('删除成功');
    loadData();
  } catch (e) {
    if (e !== 'cancel') {
      console.error(e);
      ElMessage.error('删除失败');
    }
  }
};

onMounted(loadData);
</script>

<style scoped>
.order_detail-page { padding: 16px; }

/* 顶部横幅 */
.hero {
  display: grid;
  grid-template-columns: 1.2fr 0.8fr;
  gap: 16px;
  padding: 24px 20px;
  border-radius: 16px;
  background: linear-gradient(135deg, #f3fff4 0%, #fbfffb 100%);
  border: 1px solid #d6f5d8;
  box-shadow: 0 10px 30px rgba(120, 200, 140, 0.12);
  margin-bottom: 16px;
}
.hero-left h1 { margin: 0 0 8px; font-size: 22px; color: #2e7d32; font-weight: 700; }
.hero-left p { margin: 0 0 14px; color: #5e7d63; }
.hero-stats { display: flex; gap: 14px; flex-wrap: wrap; }
.stat { background: #fff; padding: 10px 14px; border-radius: 12px; border: 1px solid #daf1db; }
.stat-num { font-size: 20px; font-weight: 700; color: #1b5e20; }
.stat-label { color: #6b8f6e; font-size: 12px; }
.hero-right { display: flex; align-items: center; justify-content: center; }
.hero-illustration { width: 160px; height: 160px; }

/* 检索卡片 */
.search-card { margin-bottom: 14px; }

/* 表格与分页 */
.pagination { margin-top: 14px; justify-content: center; }

/* 高亮行（捐赠金额大的行更显眼） */
:deep(.el-table .row-highlight) {
  --tw-shadow: 0 0 0 9999px rgba(46,125,50,0.02) inset;
  background: #fbfff9;
}

/* 进度条内文字更清晰 */
:deep(.el-progress-bar__innerText) {
  color: #1b5e20;
  font-weight: 700;
}
</style>
